package com.hy.z.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.z.utils.TreeNode;
import com.hy.z.dto.UserRoleDto;
import com.hy.z.entity.*;
import com.hy.z.mapper.*;
import com.hy.z.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.z.utils.TreeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Fhy
 * @since 2021-01-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourcesMapper roleResourcesMapper;
    @Autowired
    private ResourcesMapper resourcesMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public IPage<Role> queryAllRole(long pageNum, long pageSize) {
        return roleMapper.selectPage(new Page<>(pageNum, pageSize), null);
    }

    @Override
    public List<TreeNode> queryRoleIds(String roleId) {
        RoleResources roleResources = roleResourcesMapper.selectOne(Wrappers.<RoleResources>lambdaQuery().eq(RoleResources::getRoleId, roleId));
        String resourcesId = roleResources.getResourcesId();
        String[] split = resourcesId.split(",");
        List<Resources> resources = resourcesMapper.selectList(Wrappers.<Resources>lambdaQuery().in(Resources::getId, Arrays.asList(split)));
        return TreeUtil.getTreeNodes(resources);
    }

    @Override
    public boolean updatePermission(String roleId, String resourcesIds) {
        RoleResources roleResources = roleResourcesMapper.selectOne(Wrappers.<RoleResources>lambdaQuery().eq(RoleResources::getRoleId, roleId));
        roleResources.setResourcesId(resourcesIds);
        int i = roleResourcesMapper.updateById(roleResources);
        return i > 0;
    }

    //查询有角色下拉显示
    @Override
    public List<Role> queryRoleList() {
        return roleMapper.selectList(null);
    }

    //给用户分配角色
    @Override
    public boolean updateRoleByUserId(UserRoleDto userRoleDto) {
        boolean flag;
        UserRole userRoleInfo = userRoleMapper.selectOne(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId, userRoleDto.getUserId()));
        if (userRoleInfo == null) {//新配置角色
            UserRole userRole = new UserRole();
            BeanUtils.copyProperties(userRoleDto, userRole);
            flag = userRoleMapper.insert(userRole) > 0;
        } else {//修改角色
            userRoleInfo.setRoleId(userRoleDto.getRoleId());
            flag = userRoleMapper.updateById(userRoleInfo) > 0;
        }
        return flag;
    }
}
